package com.wine.game.wine.config;

import io.netty.channel.Channel;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.AttributeKey;
import io.netty.util.concurrent.GlobalEventExecutor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.ConcurrentHashMap;

/**
 * @description: #　　　Codes are far away from bugs with the animal protecting
 * #　　　　　　　        神兽保佑,代码无bug
 * @author: zeno fung
 * @create: 2022-05-09 11:54
 */
public class NettyConfig {
    /**
     * 定义一个channel组，管理所有的channel
     * GlobalEventExecutor.INSTANCE 是全局的事件执行器，是一个单例
     */
    private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    /**
     * 存放用户与Chanel的对应信息，用于给指定用户发送消息
     */
    private static ConcurrentHashMap<String, Channel> userChannelMap = new ConcurrentHashMap<>();


    /**
     * 存放群用户与Chanel的对应信息，用于给指定群用户发送消息
     *
     */
    private static ConcurrentHashMap<String, ChannelGroup> groupChannelMap = new ConcurrentHashMap<>();


    public static String    MESSAGE_GROUP_KEY="message:group:";

    private NettyConfig() {
    }

    /**
     * 获取channel组
     *
     * @return
     */
    public static ChannelGroup getChannelGroup() {
        return channelGroup;
    }

    /**
     * 获取用户channel map
     *
     * @return
     */
    public static ConcurrentHashMap<String, Channel> getUserChannelMap() {
        return userChannelMap;
    }

    /**
     * 获取群channel map
     *
     * @return
     */
    public static ConcurrentHashMap<String, ChannelGroup> getgroupChanneMap() {
        return groupChannelMap;
    }
    /**
     * 将用户添加到群组
     */
    public static void addUserToGroup(String groupId, String userId) {
        // 获取用户Channel
        Channel userChannel = NettyConfig.getUserChannelMap().get(userId);
        if (userChannel != null) {
            // 获取群组ChannelGroup，若没有则新建一个
            groupChannelMap.computeIfAbsent(groupId, k -> new DefaultChannelGroup(GlobalEventExecutor.INSTANCE))
                    .add(userChannel);
        }
    }
    /**
     * 从群组中移除用户
     */
    public static void removeUserFromGroup(String groupId, String userId) {
        ChannelGroup group = groupChannelMap.get(groupId);
        if (group != null) {
            Channel userChannel = userChannelMap.get(userId);
            if (userChannel != null) {
                group.remove(userChannel);
            }
        }
    }


    /**
     * 广播消息到群组
     */
    public static void broadcastToGroup(String groupId, String message) {
        ChannelGroup group = groupChannelMap.get(groupId);
        if (group != null) {
            group.writeAndFlush(new TextWebSocketFrame(message));
        }
    }
}
